#include <iostream>
#include <SDL.h>
#include <cmath>
#include <unistd.h>


using namespace std;

bool init();
void kill();
bool loop();
void error(const char* info);

SDL_Window* window;
SDL_Renderer* renderer;
SDL_Texture* texture;

int main(int argc, char** argvs){
    if( !init() )   return 1;
    while( loop() ) {
        SDL_Delay(10);
    }

    kill();
    return 0;
}




bool init()
{
    if ( SDL_Init( SDL_INIT_EVERYTHING ) < 0){
        error("initing");
        return false;
    }

    window = SDL_CreateWindow( "Example", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
    if( !window){
        error("creating window");
        return false;
    }

    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    if( !renderer){
        error("creating renderer");
        return false;
    }

    SDL_Surface* buffer = SDL_LoadBMP("test1.bmp");
    if (! buffer ){
        error("loding bmp");
        return false;
    }

    texture = SDL_CreateTextureFromSurface( renderer, buffer);
    SDL_FreeSurface( buffer);
    buffer = NULL;
    if ( !texture){
        error("creating Texture");
        return false;
    }
    return true;
}

void kill()
{
	SDL_DestroyTexture( texture );
	SDL_DestroyRenderer( renderer );
	SDL_DestroyWindow( window );
	texture = NULL;
	window = NULL;
	renderer = NULL;
	SDL_Quit();
}

bool loop()
{
    static const unsigned char* keys = SDL_GetKeyboardState( NULL);

    SDL_Event e;
    SDL_Rect dest;

    static int mx = -1, my = -1;
    static double rot = 0;

    SDL_SetRenderDrawColor( renderer, 255, 255, 255, 255);
    SDL_RenderClear( renderer);

    while( SDL_PollEvent( &e) != 0){
        switch ( e.type)
        {
        case SDL_QUIT:

            return false;
        case SDL_MOUSEMOTION:
            mx = e.motion.x;
            my = e.motion.y;
            break;
        default:
            break;
        }
    }
    if ( mx != -1){
        float wpercent = mx / 640.0f;
		float hpercent = my / 480.0f;

		// Color
		unsigned char r = round( wpercent * 255 );
		unsigned char g = round( hpercent * 255 );

		// Color mod (b will always be zero)
		SDL_SetTextureColorMod( texture, r, g, 0 );

        mx -= 320;
		my -= 240;
		rot = atan((float)my / (float)mx) * (180.0f / 3.14f);
		if (mx < 0)
			rot -= 180;

    }
    mx = my = -1;

	// Render texture
	dest.x = 240;
	dest.y = 180;
	dest.w = 160;
	dest.h = 120;
	SDL_RenderCopyEx(renderer, texture, NULL, &dest, rot, NULL, keys[SDL_SCANCODE_F] ? SDL_FLIP_VERTICAL : SDL_FLIP_NONE);

	// Update window
	SDL_RenderPresent( renderer );

    return true;
}

void error(const char* info)
{
    cout << "Error " << info << " SDL: " << SDL_GetError() << endl;
    pause();
}

